package hk.m4s.lr.repair.test.ui.goods;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import framework.common.Constant;
import framework.common.baseui.UeBaseActivity;
import framework.common.zanetwork.core.ResponseCallback;
import framework.utils.NetWorkUtil;
import framework.utils.SharedPreferencesUtils;
import hk.m4s.lr.repair.test.R;
import hk.m4s.lr.repair.test.UeApp;
import hk.m4s.lr.repair.test.model.enTableModel;
import hk.m4s.lr.repair.test.model.enValueModel;
import hk.m4s.lr.repair.test.service.AccountSerive;
import hk.m4s.lr.repair.test.ui.MainActivity;
import hk.m4s.lr.repair.test.ui.adapter.EnGoodsAdapter;
import hk.m4s.lr.repair.test.ui.adapter.EnTableAdapter;
import hk.m4s.lr.repair.test.ui.anount.LoginActivity;
import hk.m4s.lr.repair.test.ui.webview.WebViewActivity;
import hk.m4s.lr.repair.test.utils.ToastUtil;
import hk.m4s.lr.repair.test.views.BottomtoTopDialog;
import hk.m4s.lr.repair.test.views.InnerGridView;
import hk.m4s.lr.repair.test.views.listview.VListView;
import okhttp3.Response;

/**
 * Created by qi.wang on 2017/5/10.
 * 商品详情
 */

public class GoodsEventActivity extends UeBaseActivity implements OnBannerListener, VListView.IXListViewListener {
    private TabLayout tabLayout;
    private RelativeLayout show_detail;
    private LinearLayout show_en;
    private Banner banner;
    private ScrollView show_shop;
    private ProgressBar pb;
    private WebView webView;
    private ImageView failed_img;
    private TextView shop_name, goods_old_price, goods_price, goods_num, sales_return_time, carBtn;
    private TextView score_num;
    private TextView enNum;
    private InnerGridView yinxiang;
    private LinearLayout showOlidTips;
    public static List<?> images = new ArrayList<>();
    private Context context;
    private List<enValueModel.ListBean> shopList = new ArrayList<>();
    private List<enTableModel.ListBean> tableList = new ArrayList<>();
    private EnGoodsAdapter enGoodsAdapter;
    private EnTableAdapter enTableAdapter;
    private VListView vlist;
    private ImageView back;
    private String goods_id;
    private String imageUrl[];
    private String goodsPrice = "", goodsCount = "", goodsUrl = "", goodsName = "", shopId = "";
    private int pageSize = 20;
    private int pageNumber = 1;
    private String key = "";
    private String detailUrl = "";
    private int check = 1;
    private BottomtoTopDialog bottomtoTopDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        baseSetContentView(R.layout.activity_goods_event);
        hiddenFooter();
        hiddenHeader();
        // getGoodsCarBtn().setVisibility(View.VISIBLE);
        setTitleText("商品详情");
        context = this;
        goods_id = getIntent().getStringExtra("goods_id");
        bottomtoTopDialog = new BottomtoTopDialog(context, onClickListener);
//        getGoodsCarBtn().setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (TextUtils.isEmpty(SharedPreferencesUtils.getSharedPreferences(Constant.token, ""))) {
//                    Intent intent = new Intent(GoodsEventActivity.this, LoginActivity.class);
//                    startActivity(intent);
//                } else {
//                    Intent in = new Intent(GoodsEventActivity.this, GoodsCarActivity.class);
//                    startActivity(in);
//                }
//            }
//        });
        findBaseView();
        onLoad();
    }

    public void findBaseView() {
        back = (ImageView) findViewById(R.id.back);
        tabLayout = (TabLayout) findViewById(R.id.tab);
        banner = (Banner) findViewById(R.id.banner);
        show_shop = (ScrollView) findViewById(R.id.show_shop);
        show_detail = (RelativeLayout) findViewById(R.id.show_detail);
        show_en = (LinearLayout) findViewById(R.id.show_en);
        yinxiang = (InnerGridView) findViewById(R.id.yinxiang);
        showOlidTips = (LinearLayout) findViewById(R.id.showOlidTips);
        vlist = (VListView) findViewById(R.id.vlist);
        vlist.setXListViewListener(this);
        shop_name = (TextView) findViewById(R.id.shop_name);
        goods_num = (TextView) findViewById(R.id.goods_num);
        carBtn = (TextView) findViewById(R.id.carBtn);
        enNum = (TextView) findViewById(R.id.enNum);
        score_num = (TextView) findViewById(R.id.score_num);
        goods_old_price = (TextView) findViewById(R.id.goods_old_price);
        goods_price = (TextView) findViewById(R.id.goods_price);
        //yinxiang.setOnItemClickListener(clickItem);
        pb = (ProgressBar) findViewById(R.id.pb);
        pb.setMax(100);

        failed_img = (ImageView) findViewById(R.id.failed_img);
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setBuiltInZoomControls(false);
        webView.setWebChromeClient(new WebViewClient());


        //getTableList();
        tabLayout.addTab(tabLayout.newTab().setText("商品"), true);
        tabLayout.addTab(tabLayout.newTab().setText("详情"));
        tabLayout.addTab(tabLayout.newTab().setText("评价"));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    show_shop.setVisibility(View.VISIBLE);
                    show_detail.setVisibility(View.GONE);
                    show_en.setVisibility(View.GONE);
                } else if (tab.getPosition() == 1) {
                    show_shop.setVisibility(View.GONE);
                    show_en.setVisibility(View.GONE);
                    show_detail.setVisibility(View.VISIBLE);
                } else {
                    show_shop.setVisibility(View.GONE);
                    show_detail.setVisibility(View.GONE);
                    show_en.setVisibility(View.VISIBLE);
                    // getcommentList("1");
                }

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        banner.isAutoPlay(false);
        banner.setDelayTime(3500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.RIGHT);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        banner.setOnBannerListener(this);

        enGoodsAdapter = new EnGoodsAdapter(context, shopList);
        vlist.setAdapter(enGoodsAdapter);
        enTableAdapter = new EnTableAdapter(context, tableList);
        yinxiang.setAdapter(enTableAdapter);
        // getGoodsEvent();
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if(shopModelList.size()>0){
//            getShowRedView().setVisibility(View.VISIBLE);
//            if(shopModelList.size()>99){
//                getShowRedView().setText("99");
//            }else{
//                getShowRedView().setText(shopModelList.size()+"");
//            }
//        }else{
//            getShowRedView().setVisibility(View.GONE);
//        }
    }

    public class GlideImageLoader extends ImageLoader {
        @Override
        public void displayImage(Context context, Object path, ImageView imageView) {
            Glide.with(context).load(path).placeholder(R.mipmap.sebei_logo).error(R.mipmap.sebei_logo).into(imageView);
        }

    }

    @Override
    public void OnBannerClick(int position) {
//        Intent in = new Intent(GoodsEventActivity.this, ImageLookActivity.class);
//        in.putExtra("imgUrl", imageUrl);
//        startActivity(in);
    }

    private class WebViewClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            pb.setProgress(newProgress);
            if (newProgress == 100) {
                pb.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, newProgress);
        }

    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.carBtn:
                if (check == 1) {
                    check = 2;
                    SharedPreferencesUtils.addgetSharedPreferences(Constant.check, String.valueOf(check));
                    Drawable drawable = getResources().getDrawable(R.mipmap.carled_img);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    carBtn.setCompoundDrawables(null, drawable, null, null);
                } else {
                    check = 1;
                    SharedPreferencesUtils.addgetSharedPreferences(Constant.check, String.valueOf(check));
                    Drawable drawable = getResources().getDrawable(R.mipmap.carle_img);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    carBtn.setCompoundDrawables(null, drawable, null, null);
                }
                break;
            case R.id.failed_img:
                webView.loadUrl(detailUrl);
                break;
            case R.id.selct_ad:

                break;
            case R.id.couponLayout:
                bottomtoTopDialog.show();
                break;
            case R.id.shopBtn:
                Intent shopBtnIn = new Intent(GoodsEventActivity.this, GoodsShopActivity.class);
                shopBtnIn.putExtra("goods_id", goods_id);
                shopBtnIn.putExtra("shopId", shopId);
                startActivity(shopBtnIn);
                finish();
                break;
            case R.id.selct_car:
                if (TextUtils.isEmpty(SharedPreferencesUtils.getSharedPreferences(Constant.token, ""))) {
                    Intent intent = new Intent(GoodsEventActivity.this, LoginActivity.class);
                    startActivity(intent);
                } else {
                    Intent in = new Intent(GoodsEventActivity.this, SlectGoodsSignActivity.class);
                    in.putExtra("gocar", "1");
                    in.putExtra("goods_id", goods_id);
                    //in.putExtra("goodsCount", goodsCount);
                    in.putExtra("goodsUrl", goodsUrl);
                    in.putExtra("goodsName", goodsName);
                    in.putExtra("shopId", shopId);
                    startActivityForResult(in, 10);
                }
                break;
            case R.id.selct_buy:
//                if (TextUtils.isEmpty(SharedPreferencesUtils.getSharedPreferences(Constant.token, ""))) {
//                    Intent intent = new Intent(GoodsEventActivity.this, LoginActivity.class);
//                    startActivity(intent);
//                } else {
//                    Intent ins = new Intent(GoodsEventActivity.this, SlectGoodsSignActivity.class);
//                    ins.putExtra("gocar", "2");
//                    ins.putExtra("goods_id", goods_id);
//                    //ins.putExtra("goodsCount", goodsCount);
//                    //ins.putExtra("goodsPrice", goodsPrice);
//                    ins.putExtra("goodsUrl", goodsUrl);
//                    ins.putExtra("goodsName", goodsName);
//                    ins.putExtra("shopId", shopId);
//                    startActivityForResult(ins, 101);
//                }
                Intent intent=new Intent(GoodsEventActivity.this,OrderSureActivity.class);
                startActivity(intent);
                break;
            case R.id.push_on:
                Intent win = new Intent(GoodsEventActivity.this, WebViewActivity.class);
                win.putExtra("show", "2");
                win.putExtra("title", "正品授权");
                win.putExtra("url", " ");
                startActivity(win);
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

        } else {
            switch (requestCode) {
                case 10: // 我的收货地址

//                    if(shopModelList.size()>0){
//                        int count=shopModelList.size();
//                        getShowRedView().setVisibility(View.VISIBLE);
//                        if(count>99){
//                            getShowRedView().setText("99");
//                        }else{
//                            getShowRedView().setText(count+1+"");
//                        }
//                    }else{
//                        getShowRedView().setVisibility(View.GONE);
//                    }
                    break;
                default:
                    break;
            }
        }


    }
//    public void getGoodsEvent() {
//        Map<String, Object> parmas = new HashMap<>();
//        parmas.put("device_type", Constant.device_type);
//        parmas.put("userId", SharedPreferencesUtils.getSharedPreferences(Constant.userId, ""));
//        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.token, ""));
//        parmas.put("goods_id", goods_id);
//        AccountSerive.getGoodsEvent(context, parmas, new ResponseCallback<GoodsModel>() {
//            @Override
//            public void onSuccess(GoodsModel userinfoModel) {
//                shop_name.setText(userinfoModel.getGoods_name());
//                goodsName=userinfoModel.getGoods_name();
//                goods_price.setText("¥" + userinfoModel.getPrice());
//                shopId=userinfoModel.getShop_id();
////                if()
////                goods_old_price.setText("¥" + userinfoModel.get);
////                goods_old_price.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
//                goods_num.setText(userinfoModel.getGoods_sell_count());
//                sales_return_time.setText(userinfoModel.getSales_return_time() + "天无理由退货");
//                score_num.setText("¥" + userinfoModel.getFreight());
//                goodsCount = userinfoModel.getGoods_inventory_count();
//                String img = userinfoModel.getImages();
//                imageUrl = img.split(",");
//                goodsUrl = imageUrl[0];
//                List list = Arrays.asList(imageUrl);
//                images = new ArrayList(list);
//                //设置图片集合
//                banner.setImages(images);
//                //banner设置方法全部调用完毕时最后调用
//                banner.start();
//                banner.stopAutoPlay();
//                detailUrl=userinfoModel.getDetail();
//                if (NetWorkUtil.isNetworkAvaliable(context)) {
//                    webView.setWebViewClient(new android.webkit.WebViewClient() {
//                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                            view.loadUrl(url);
//                            return true;//ture为在webview中打开
//
//                        }
//
//                        @Override
//                        public void onReceivedError(WebView view, int errorCode,
//                                                    String description, String failingUrl) {
//                            // TODO Auto-generated method stub
//                            super.onReceivedError(view, errorCode, description, failingUrl);
//                            failed_img.setVisibility(View.VISIBLE);
//
//                        }
//                    });
//                    webView.loadUrl(userinfoModel.getDetail());
//                } else {
//                    failed_img.setVisibility(View.VISIBLE);
//                }
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
//
//            }
//        });
//
//    }

    private void onLoad() {
        vlist.stopRefresh();
        vlist.stopLoadMore();
        Date data = new Date(System.currentTimeMillis());
        vlist.setRefreshTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
                Locale.CHINA).format(data));
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        // getData();
        vlist.setPullLoadEnable(true);
        pageNumber = 1;
        //getcommentList("1");
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        vlist.setPullRefreshEnable(true);
        pageNumber++;
        // getcommentList("2");
    }

    //    public void getcommentList(final String refreshType) {
//        Map<String, Object> parmas = new HashMap<>();
//        parmas.put("device_type", Constant.device_type);
//        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.evaluate_token,""));
//        parmas.put("commentObject", "12");
//        parmas.put("tabsKey", key);
//        parmas.put("pageNum", pageNumber);
//        parmas.put("pageSize", pageSize);
//        AccountSerive.getcommentList(context, parmas, new ResponseCallback<enValueModel>() {
//            @Override
//            public void onSuccess(enValueModel userinfoModel) {
//                onLoad();
//                if(userinfoModel!=null) {
//                    if (userinfoModel.getGood() != null) {
//                        enNum.setText(userinfoModel.getGood());
//                    }
//                    switch (refreshType) {
//                        case "1":
//                            shopList.clear();
//                            if (userinfoModel.getList() != null) {
//                                showOlidTips.setVisibility(View.GONE);
//                                shopList.addAll(userinfoModel.getList());
//
//                                if (userinfoModel.getList().size() <= pageSize) {
//                                    vlist.removeFooterView();
//                                    vlist.setPullLoadEnable(false);
//                                } else {
//                                    vlist.showFooterView();
//                                    vlist.setPullLoadEnable(true);
//                                }
//                            } else {
//                                showOlidTips.setVisibility(View.VISIBLE);
//                            }
//                            break;
//                        case "2":
//                            shopList.addAll(userinfoModel.getList());
//                            if (userinfoModel.getList().size() <= pageSize) {
//                                vlist.removeFooterView();
//                                vlist.setPullLoadEnable(false);
//                            }
//                            break;
//                    }
//                    enGoodsAdapter.notifyDataSetChanged();
//                }else{
//                    showOlidTips.setVisibility(View.VISIBLE);
//                }
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
//
//            }
//        });
//
//    }
//
//    public void getTableList() {
//        Map<String, Object> parmas = new HashMap<>();
//        parmas.put("device_type", Constant.device_type);
//        parmas.put("token", SharedPreferencesUtils.getSharedPreferences(Constant.evaluate_token,""));
//        AccountSerive.getTableList(context, parmas, new ResponseCallback<enTableModel>() {
//            @Override
//            public void onSuccess(enTableModel userinfoModel) {
//                tableList.clear();
//                if (userinfoModel.getList() != null) {
//                    enTableModel.ListBean bean=new enTableModel.ListBean();
//                    bean.setKeycode("-1");
//                    bean.setName("全部");
//                    tableList.addAll(userinfoModel.getList());
//                    tableList.add(0,bean);
//                }
//                enTableAdapter.flag=0;
//                enTableAdapter.notifyDataSetChanged();
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, String errorMsg, Exception e) {
//
//            }
//        });
//
//    }
//    AdapterView.OnItemClickListener clickItem = new AdapterView.OnItemClickListener() {
//
//        @Override
//        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
//                                long arg3) {
//            // TODO Auto-generated method stub
//            pageNumber = 1;
//            enTableModel.ListBean model=tableList.get(arg2);
//            enTableAdapter.flag=arg2;
//            enTableAdapter.notifyDataSetChanged();
//            if(model.getKeycode().equals("-1")){
//               key="";
//            }else {
//                key = model.getKeycode();
//            }
//            getcommentList("1");
//        }
//
//    };
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.close:
                    if (bottomtoTopDialog != null) {
                        bottomtoTopDialog.dismiss();
                    }
                    break;
                case R.id.btn_cancel:
                    showToast();
                    if (bottomtoTopDialog != null) {
                        bottomtoTopDialog.dismiss();
                    }
                    break;
            }
        }
    };

    public void showToast(){
        Toast customToast = new Toast(UeApp.getAppContext());
        View customView = LayoutInflater.from(UeApp.getAppContext()).inflate(R.layout.custom_toast,null);
        ImageView img = (ImageView) customView.findViewById(R.id.iv);
        TextView tv = (TextView) customView.findViewById(R.id.tv);
        //设置ImageView的图片
        img.setBackgroundResource(R.mipmap.sucessimg);
        //设置textView中的文字
        tv.setText("领取成功");
        //设置toast的View,Duration,Gravity最后显示
        customToast.setView(customView);
        customToast.setDuration(Toast.LENGTH_SHORT);
        customToast.setGravity(Gravity.CENTER,0,0);
        customToast.show();
    }
}
